/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;

import java.io.IOException;
import java.net.Socket;
import model.DBConnection;

/**
 *
 * @author Tobias
 */
public class ClientThread extends Thread {

    private final String SERVERIP = "localhost";
    private final int SERVERPORT = 4444;
    private final String HOST = "dunk.it.jcu.edu.au";

    private static DBConnection conn = null;

    private static Socket sock = null;
    private static boolean connectionClosed = false;

    private static ClientThread instance = null;

    public ClientThread() {

        try {
            // try connect to database
            tryConnect(HOST);
            sock = new Socket(SERVERIP, SERVERPORT);
            ClientView.printMessage("Connected to server: " + sock + "\n");
        } catch (Throwable e) {
            ClientView.printMessage("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void closeConnection() throws IOException {
        connectionClosed = true;
        sock.close();
        conn.closeConnection();
    }

    public static boolean checkConnectionClosed() {
        return connectionClosed;
    }

    public static ClientThread getInstance() {
        if (instance == null) {
            instance = new ClientThread();
        }
        return instance;
    }

    /**
     * Attempts to connect to the database based on host.
     * Host sent though command line argument.
     *
     * @param host host name passed by command line argument
     */
    public void tryConnect(String host) {
       conn = DBConnection.getInstance();
       conn.connect(host);
    }

}
